package ld.servlet;

import com.alibaba.fastjson.JSON;
import ld.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: Liudao
 * @Date: 2022-08-05-14:40
 * @Description:
 */
@WebServlet("/user")
public class UserServlet extends HttpServlet {
//    @Autowired
//    private UserService userService;


    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置响应页面的字符编码
        resp.setContentType("text/html;charset=utf-8");
        //得到请求参数
        String cmd = req.getParameter("cmd");
        //根据参数调用不同方法
        if (!StringUtils.isEmpty(cmd)) {
            if ("login".equals(cmd)) {
                login(req,resp);
            }else if ("info".equals(cmd)){
                info(req,resp);
            }
        }
    }

    private void info(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //1. 定义R对象 
        R r = R.ok().data("name","admin") 
                .data("avatar","https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif"); 
        //2. 将r对象输出到前端页面 
        resp.getWriter().println(JSON.toJSONString(r)); 
        resp.getWriter().flush();
    }

    private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //定义R对象
        R r = R.ok().data("token", 1);
        //输出到前端页面
        resp.getWriter().println(JSON.toJSONString(r));
        resp.getWriter().flush();
    }
}
